import { EditorProvider, useCurrentEditor } from "@tiptap/react";
import { Document } from "../extensions/Document";
import { Text } from "../extensions/Text";
import { Paragraph } from "../extensions/Paragraph";
import { Bold } from "../extensions/Bold";
import Italic from "@tiptap/extension-italic";
import { Code } from "../extensions/Code";
import TagExtension from "../extensions/TagExtension";
import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCursor from "@tiptap/extension-collaboration-cursor";
import { cursorRender } from "./cursorRender";
const ydoc = new Y.Doc();
const provider = new WebsocketProvider(
  "ws://localhost:1234",
  "yjs-editor-room",
  ydoc
);

// 生成随机颜色
function getRandomColor() {
  return `#${Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padStart(6, "0")}`;
}

// 生成随机用户名
function getRandomName() {
  return `user-${Math.random().toString(36).slice(2, 8)}`;
}

const Toolbar = () => {
  const { editor } = useCurrentEditor();
  if (!editor) return null;

  const bold = () => {
    editor.chain().focus().toggleBold().run();
  };
  const italic = () => {
    editor.chain().focus().toggleItalic().run();
  };
  const undo = () => {
    editor.chain().focus().undo().run();
  };
  const redo = () => {
    editor.chain().focus().redo().run();
  };
  return (
    <div>
      <button onClick={bold}>加粗</button>
      <button onClick={italic}>斜体</button>
      <button onClick={undo}>撤销</button>
      <button onClick={redo}>重做</button>
    </div>
  );
};

export function Editor() {
  return (
    <EditorProvider
      extensions={[
        Document,
        Text,
        Paragraph,
        Bold,
        Italic,
        Code,
        TagExtension,
        Collaboration.configure({
          document: ydoc,
        }),
        CollaborationCursor.configure({
          provider,
          user: {
            name: getRandomName(),
            color: getRandomColor(),
          },
          render: cursorRender,
        }),
      ]}
    >
      <Toolbar />
    </EditorProvider>
  );
}
